package com.qf.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtils {

    @Value("${jwt.securt}")
    private String securt;

    public String signToken(Map map){
        //1.声明 算法以及 密钥
        Algorithm algorithm = Algorithm.HMAC256(securt);
        //2.声明头部信息
        Map headMap = new HashMap<>();
        headMap.put("typ","JWT");
        headMap.put("alg","HS256");
        //3.创建token 载荷信息
        String token = JWT.create().withHeader(headMap)
                //1.签发人
                .withIssuer("qianfeng")
                //2.主题
                .withSubject("login")

                //3.受众
                .withAudience("users")
                //自定义载荷
                .withClaim("name", map.get("name").toString())
                .withClaim("id",map.get("id").toString())
                .sign(algorithm);

        return token;
    }

    public Integer verfiy(String token){
        try {
            //1.声明算法
            Algorithm algorithm = Algorithm.HMAC256(securt);
            //声明解密对象
            JWTVerifier jwtVerifier = JWT.require(algorithm).withIssuer("qianfeng").build();
            //使用解密对象对token进行解密
            DecodedJWT verify = jwtVerifier.verify(token);
            String id = verify.getClaim("id").asString();
            return  Integer.valueOf(id);
        }catch (Exception e){
            System.out.println(e.getMessage());
            return 0;

        }
    }
}
